package com.zuo;

import org.w3c.dom.Node;

import java.util.Stack;

public class MinStackTest {
    public static void main(String[] args) {
        MinStack minstack = new MinStack();
        minstack.push(3);
        minstack.push(6);
        minstack.push(45);
        minstack.push(1);

        Integer top =  minstack.top();

        Integer min = minstack.getMin();

        minstack.pop();

        Integer min2 = minstack.getMin();

        minstack.pop();

        Integer min3 = minstack.getMin();

    }
}
class MinStack {

    private Stack<Integer> data;
    private Stack<Integer> helper;

    /** initialize your data structure here. */
    MinStack() {
        data = new Stack<>();
        helper = new Stack<>();
    }

    /*
    * 辅助栈和数据栈不同步
    * 1:辅助栈为空时,必须放入新进的数
    * 2:新来的数小于或等于辅助栈顶的元素时,才放入辅助站
    * 3:出栈时,辅助栈的栈顶元素等于数据栈的栈顶元素,才出栈,即"出栈保持同步";
    * */

    void push(int x) {
        data.add(x);
        if (helper.isEmpty() || helper.peek() >= x){
            helper.add(x);
        }
    }

    void pop() {
        int top = data.pop();
        if (top == helper.peek()) {
            helper.pop();
        }
    }

    int top() {
        if (!data.isEmpty()) {
            return data.peek();
        }
        throw new RuntimeException("栈为空,此操作非法");
    }

    int getMin() {
        if (!helper.isEmpty()){
            return helper.peek();
        }
        throw new RuntimeException("栈为空,此操作非法");
    }
};

